package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import cn.jpush.android.api.JPushInterface;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.IGetServicesDataCallBack;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 访客拦截
 */
public class RegisterActivity2 extends BaseActivity {
    @ViewInject(id=R.id.fill_view,click = "fill_view_click")
    private LinearLayout fill_view;
    @ViewInject(id = R.id.register_layout2)
    private LinearLayout register_layout2;
    /**
     * 进行登录
     */
    @ViewInject(id = R.id.has_account_tv, click = "has_account_tv_click")
    private TextView has_account_tv;

    @ViewInject(id = R.id.third_account_tv, click = "third_account_tv_click")
    private TextView third_account_tv;
    /**
     * 注册
     */
    @ViewInject(id = R.id.user_register_bt, click = "register_bt_click")
    private TextView user_register_bt;
    /**
     * 输入账号
     */
    @ViewInject(id = R.id.user_account_ed)
    private EditText user_account_ed;
    /**
     * 请输入验证码
     */
    @ViewInject(id = R.id.user_code_ed)
    private EditText user_code_ed;
    /**
     * 请输入邮箱
     */
    @ViewInject(id = R.id.user_email_ed)
    private EditText user_email_ed;
    /**
     * 请输入密码
     */
    @ViewInject(id = R.id.user_pwd_ed)
    private EditText user_pwd_ed;

    /**
     * 注册协议
     */
    @ViewInject(id = R.id.agree_tv, click = "agreement_click")
    private TextView agreement;

    /**
     * 发送验证码
     */
    @ViewInject(id = R.id.btn_send_code, click = "send_code_click")
    private TextView btn_send_code;
    private String registerName;
    private String getCode;  //验证码
    private TimeCount time; //定时器
    private String passWord;
    private String getEmail;//邮箱
    private int flag;     //用来判断是进入下一个界面还是finish
    private int requestLogin = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().getIntExtra(ExtraKeys.Key_Msg1, 0) == 1) {
            flag = 1;
        } else {
            flag = 0;
        }
        setContentView(R.layout.activity_user_register2);
        addUnderLine(agreement);
        addUnderLine(has_account_tv);
        addUnderLine(third_account_tv);
        sendCodeClick();
        time = new TimeCount(120000, 1000);
    }

    /**
     * 空白处 结束
     * @param view
     */
    public void fill_view_click(View view){
        finish();
    }

    /**
     * 获取验证码（防止网络延时发送多条验证码）
     */
    public void sendCodeClick() {
        btn_send_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (judgeMobileNo()) {
                    getData_UserSendCode();
                }
            }
        });
    }

    /**
     * 登录
     */
    public void has_account_tv_click(View view) {
        Intent intentLogin = new Intent(this, LoginActivity.class);
        intentLogin.putExtra(ExtraKeys.Key_Msg1, flag);
        intentLogin.putExtra(ExtraKeys.Key_Msg2, 1);
        startActivityForResult(intentLogin, requestLogin);
        register_layout2.setVisibility(View.GONE);
    }

    public void third_account_tv_click(View view) {
        Intent intentLogin = new Intent(this, LoginActivity.class);
        intentLogin.putExtra(ExtraKeys.Key_Msg1, flag);
        intentLogin.putExtra(ExtraKeys.Key_Msg2, 2);
        startActivityForResult(intentLogin, requestLogin);
        register_layout2.setVisibility(View.GONE);
    }

    /**
     * 注册协议
     *
     * @param view
     */
    public void agreement_click(View view) {
        jumpTo(UrlWebviewActivity.class);
    }


    /**
     * 调用发送验证码接口
     */
    private void getData_UserSendCode() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("Phone", registerName);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_RegisterGetCode);
        queue.setWhat(GetDataConfing.What_RegisterGetCode);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }


    /**
     * 数据回调
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                JsonMap<String, Object> data = JsonParseHelper.getJsonMap(entity.getInfo());
                if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
                        entity.getInfo())) {
                    if (entity.getWhat() == GetDataConfing.What_RegisterGetCode) {
                        time.start();
                        btn_send_code.setEnabled(false);
                    } else if (entity.getWhat() == GetDataConfing.what_CheckRegister) {
                        /**
                         * 注册信息保存
                         */
                        List<JsonMap<String, Object>> info = data.getList_JsonMap("Info");
                        JsonMap<String, Object> dataInfo = info.get(0);
                        Utils.saveUserInfos(mContext, dataInfo);
                        Utils.saveUserLoginStyle(mContext, false);
                        toast.showToast(R.string.regisger_success);
                        loadingToast.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                } else {

                }
            } else {

                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }
    };

    /**
     * 判断手机号码
     */

    public boolean judgeMobileNo() {
        registerName = user_account_ed.getText().toString();
        if (TextUtils.isEmpty(registerName)) {
            //手机号码为空的情况
            toast.showToast(R.string.register_name_null);
            return false;
        } else if (!StringUtil.isMobileNO(registerName)) {
            toast.showToast(R.string.phone_formal_error);
            return false;
        }
        return true;
    }

    //验证码倒计时
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            //参数依次为总时长,和计时的时间间隔
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            btn_send_code.setText(getString(R.string.revalidation));
            getCode = "";
            btn_send_code.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btn_send_code.setText(millisUntilFinished / 1000 + getString(R.string.second));
        }
    }

    public void register_bt_click(View view) {
        if (registerJudge()) {
            getData_UserSubmitCode();
        }
    }

    /**
     * 注册提交
     */
    private void getData_UserSubmitCode() {

        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("UserAccount", registerName);
        params.put("Phone", registerName);
        params.put("Password", passWord);
        params.put("TwoPassword", passWord);
        params.put("Email", getEmail);
        params.put("Code", getCode);
        params.put("TempUserAccount", MyApplication.getInstance().getTempUserAccount());
        params.put("Tag", JPushInterface.getRegistrationID(this));
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_CheckRegister);
        queue.setWhat(GetDataConfing.what_CheckRegister);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }


    /**
     * 注册的判断
     */

    public boolean registerJudge() {
        getCode = user_code_ed.getText().toString();
        passWord = user_pwd_ed.getText().toString();
        getEmail = user_email_ed.getText().toString();
        if (!judgeMobileNo()) {
            return false;
        }
        if (TextUtils.isEmpty(getCode)) {
            toast.showToast(R.string.pls_input_code);
            return false;
        }
        if (TextUtils.isEmpty(passWord)) {
            toast.showToast(R.string.register_password_null);
            return false;
        } else {
            if (!isPasswordAuthentication(passWord)) {
                return false;
            }
        }
        if (TextUtils.isEmpty(getEmail)) {
//			toast.showToast(R.string.email_cannot_empty);
//			isemail = false;
            return true;
        } else {
            if (!StringUtil.isEmail(getEmail)) {
                toast.showToast(R.string.email_style_error);
                return false;
            } else {
                return true;
            }
        }

    }

    /**
     * 密码判断
     */
    public boolean isPasswordAuthentication(String password) {
        if (!StringUtil.passwordAuthenticationLength(password)) {
            toast.showToast(R.string.register_passwordRule);
            return false;
        } else if (!StringUtil.passwordAuthentication(password)) {
            toast.showToast(R.string.password_format_error);
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.d(TAG,"resultCode:"+resultCode);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        } else {
            register_layout2.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
    }
}
